import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:go_router/go_router.dart';
import 'package:leader_doctor_flutter/common/data/app.dart';
import 'package:leader_doctor_flutter/common/http/api.dart';
import 'package:leader_doctor_flutter/common/http/http_client.dart';
import 'package:leader_doctor_flutter/common/utils/date_utils.dart';
import 'package:leader_doctor_flutter/common/utils/image_utils.dart';
import 'package:leader_doctor_flutter/common/utils/string_utils.dart';
import 'package:leader_doctor_flutter/common/widget/comm_widget.dart';
import 'package:leader_doctor_flutter/router/router.dart';
import 'package:leader_doctor_flutter/styles/colors.dart';
import 'package:leader_doctor_flutter/ui/wallet/model/dict.dart';
import 'package:leader_doctor_flutter/ui/wallet/model/income_order.dart';
import 'package:leader_doctor_flutter/ui/wallet/model/new_order.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';

/// @Author lixiaobin
/// @Date 2024/2/1
/// @Description 输入明细
class IncomeListPage extends StatefulWidget {
  const IncomeListPage({super.key});

  @override
  State<IncomeListPage> createState() => _IncomeListPageState();
}

class _IncomeListPageState extends State<IncomeListPage> {
  var _dateType = 'appAll';
  var _walletType = '';
  List<DictModel>? _walletTypeList;
  final _orderList = <NewOrder?>[];
  var _pageNo = 1;
  final _pageSize = 20;
  var _totalIncomeForType = '0.00';
  final _refreshController = RefreshController(initialRefresh: false);

  void _onRefresh() async {
    _pageNo = 1;
    _getIncomeList();
    _refreshController.refreshCompleted();
  }

  void _onLoading() async {
    _pageNo++;
    _getIncomeList();
    _refreshController.loadComplete();
  }

  @override
  void initState() {
    super.initState();
    _getWalletType();
    _getIncomeList();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: CommWidget.getCommAppbar(context),
        body: Container(
          color: ColorRes.colorf7f7f7,
          child: Column(
            children: [
              SizedBox(height: 20.w),
              Row(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  _buildTimeButton('全部', 'appAll'),
                  SizedBox(width: 15.w),
                  _buildTimeButton('今天', 'appDay'),
                  SizedBox(width: 15.w),
                  _buildTimeButton('本月', 'appMonth'),
                  SizedBox(width: 15.w),
                  _buildTimeButton('本年', 'appYear'),
                ],
              ),
              SizedBox(height: 20.w),
              SingleChildScrollView(
                  scrollDirection: Axis.horizontal,
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: _walletTypeList
                            ?.map((e) => _buildTypeButton(e.name ?? '', _walletType == e.code, e.code ?? ''))
                            .toList() ??
                        [],
                  )),
              SizedBox(height: 25.w),
              Row(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  Text('合计：',
                      textAlign: TextAlign.center,
                      style: TextStyle(
                        color: ColorRes.colorafacb0,
                        fontSize: 14.sp,
                      )),
                  Text(_totalIncomeForType,
                      textAlign: TextAlign.center,
                      style: TextStyle(
                        color: ColorRes.color333333,
                        fontSize: 16.sp,
                      ))
                ],
              ),
              SizedBox(height: 25.w),
              Expanded(
                  child: Stack(
                children: [
                  Visibility(
                    visible: _orderList.isEmpty,
                    child: CommWidget.buildEmptyView(),
                  ),
                  Visibility(visible: _orderList.isNotEmpty, child: _buildSmartRefresher()),
                ],
              )),
            ],
          ),
        ));
  }

  /// 刷新组件
  SmartRefresher _buildSmartRefresher() {
    return SmartRefresher(
      controller: _refreshController,
      enablePullDown: true,
      enablePullUp: true,
      onRefresh: _onRefresh,
      onLoading: _onLoading,
      child: ListView.builder(
        shrinkWrap: true,
        itemBuilder: (c, i) => _buildItem(c, i),
        itemCount: _orderList.length,
      ),
    );
  }

  /// 日期选择按钮
  Widget _buildTimeButton(String title, String type) {
    bool isSelect = _dateType == type;
    return GestureDetector(
        behavior: HitTestBehavior.opaque,
        onTap: () {
          _dateType = type;
          _onRefresh();
        },
        child: Container(
            width: 65.w,
            height: 30.w,
            alignment: Alignment.center,
            decoration: BoxDecoration(
                borderRadius: BorderRadius.circular(5.w),
                color: isSelect ? ColorRes.colorMain : ColorRes.colore6e6ff),
            child: Text(
              title,
              textAlign: TextAlign.center,
              style: TextStyle(color: isSelect ? ColorRes.white : ColorRes.colorMain, fontSize: 15.sp, height: 1.2),
            )));
  }

  /// 类型选择按钮
  Widget _buildTypeButton(String title, bool isSelect, String code) {
    return GestureDetector(
        behavior: HitTestBehavior.opaque,
        onTap: () {
          _walletType = code;
          _onRefresh();
        },
        child: Container(
            width: 80.w,
            height: 30.w,
            margin: EdgeInsets.only(left: 15.w),
            alignment: Alignment.center,
            decoration: BoxDecoration(
                borderRadius: BorderRadius.circular(15.w),
                color: isSelect ? ColorRes.colorf8b751 : ColorRes.colore6e6e6),
            child: Text(title,
                textAlign: TextAlign.center,
                softWrap: false,
                style:
                    TextStyle(color: isSelect ? ColorRes.white : ColorRes.color999999, fontSize: 15.sp, height: 1.2))));
  }

  /// 收入列表组件
  Widget _buildItem(BuildContext c, int i) {
    var incomeOrder = _orderList[i];
    return GestureDetector(
        behavior: HitTestBehavior.opaque,
        onTap: () {
          var path = '${PageUrl.walletIncomeDetail}?subOrderNo=${incomeOrder?.subOrderNo}';
          context.push(path);
        },
        child: SizedBox(
            height: 96.w,
            child: Column(
              children: [
                Expanded(
                    child: Row(children: [
                  SizedBox(width: 12.w),
                  ClipRRect(
                      borderRadius: BorderRadius.circular(24.w),
                      child: ImageLoader.loadPatientAvatar(incomeOrder?.icon, size: Size(48.w, 48.w))),
                  SizedBox(width: 12.w),
                  Expanded(
                      child: Column(
                          mainAxisAlignment: MainAxisAlignment.spaceAround,
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                        Row(
                          children: [
                            SizedBox(
                                width: 80.w,
                                child: Text(incomeOrder?.sysOrder?.userName ?? '',
                                    maxLines: 1,
                                    overflow: TextOverflow.ellipsis,
                                    style: TextStyle(
                                        color: ColorRes.color333333, fontSize: 16.sp, fontWeight: FontWeight.bold))),
                            Text(incomeOrder?.sysOrder?.orderTypeVal ?? '',
                                style: TextStyle(
                                    color: ColorRes.colorffb50c, fontSize: 16.sp, fontWeight: FontWeight.bold)),
                            SizedBox(width: 15.w),
                            CommWidget.buildConsultTypeBtn('义诊', isShow: incomeOrder?.promotionChannel == '4'),
                          ],
                        ),
                        Text(MyDateUtils.format(incomeOrder?.payTime, 'yyyy-MM-dd HH:mm:ss'),
                            style: TextStyle(color: ColorRes.color999999, fontSize: 14.sp)),
                      ])),
                  Row(
                    children: [
                      Text('￥${StringUtils.formatNumber(incomeOrder?.totalFee)}',
                          style: TextStyle(color: ColorRes.colorff6666, fontSize: 15.sp)),
                      SizedBox(width: 12.w),
                      ImageLoader.loadAsset('grey_setup.webp', 12.w),
                      SizedBox(width: 12.w)
                    ],
                  )
                ])),
                Container(
                  color: ColorRes.colord5d5d5,
                  height: 1,
                  margin: EdgeInsets.only(left: 75.w),
                )
              ],
            )));
  }

  /// 收入类型字典
  _getWalletType() async {
    var response = await HttpClient.get(HttpRequest(Api.getByDict, urlParams: {'dictType': 'wallet_type'}));
    var serviceResult = ServiceResult<List<DictModel>>.list(
        response, (list) => (list ?? []).map((e) => DictModel.fromJson(e)).toList());
    if (serviceResult.success) {
      _walletTypeList = serviceResult.responseBody;
      setState(() {});
    }
  }

  /// 收入明细
  _getIncomeList() async {
    var user = App.instance.userInfo;
    var response = await HttpClient.post(HttpRequest(Api.incomeList, urlParams: {
      'userId': user?.id ?? '',
      'timeType': _dateType,
      'orderType': _walletType,
      'pageIndex': _pageNo,
      'pageSize': _pageSize,
    }));
    var serviceResult = ServiceResult<IncomeOrder>(response, (map) => IncomeOrder.fromJson(map));
    if (serviceResult.success) {
      var incomeOrder = serviceResult.responseBody;
      if (_pageNo == 1) {
        _orderList.clear();
      }
      _orderList.addAll(incomeOrder?.orderList ?? []);
      _totalIncomeForType = StringUtils.formatNumber(incomeOrder?.count);
      setState(() {});
    }
  }
}
